﻿using UnityEngine;
using System.Collections;

using System.Collections.Generic;



public class EnemySpawnController : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
		StartCoroutine(SpawnEnemy());
	}
	
	// Update is called once per frame
	void Update () {
		if(!string.IsNullOrEmpty(Input.inputString))
		{
			currentWord += Input.inputString;
			bool codeMatches = false;
			
			foreach (EnemyController enemy in enemies)
			{
				if( enemy.destructCode != "" && enemy.hacked)
				{
					if( currentWord.Contains(enemy.destructCode))
					{
						StartCoroutine(enemy.Kill());
						codeMatches = true;
					}
				}
			}
			
			if( codeMatches)
				currentWord = "";
		}
	
	}
	
	
	public Object enemyPrefab;
	
	public int firstEnemyDelay = 1;
	
	public float minInterval = 4;
	
	public float maxInterval = 15;
	
	public float minMovementTime = 20;
	
	public float maxMovementTime = 50;
	
	
	public float destructCodeChance = 60;
	
	public string[] wordKeys;
	
	private List<EnemyController> enemies;
	
	public static EnemySpawnController instance;
	
	public string currentWord;
	
	
	IEnumerator SpawnEnemy()
	{
		float delay = firstEnemyDelay;
		
		while(true)
		{
			yield return new WaitForSeconds(delay);
			
			EnemyController newEnemy = NGUITools.AddChild(gameObject, enemyPrefab as GameObject).GetComponent<EnemyController>();
			
			newEnemy.Initialize(Random.Range(minMovementTime, maxMovementTime));
			
			delay = Random.Range(minInterval, maxInterval);
			
			string randomCode = "";
				
			if( Random.Range(0, 100f) < destructCodeChance)
			{
				randomCode = GetRandomWord();
			}
			
			newEnemy.SetDesctuctCode(randomCode);
			
			enemies.Add(newEnemy);
		}
		
	}
	
	private string GetRandomWord()
	{
		return wordKeys[Random.Range(0, wordKeys.Length)];
	}
	
	public void EnemyDestroyed(EnemyController destroyedEnemy)
	{
		enemies.Remove(destroyedEnemy);
	}
	
	void Awake()
	{
		instance = this;
		
		enemies = new List<EnemyController>();
	}
	
	
	
}
